#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    clint_num=0;
    ui->setupUi(this);
    m_tcps=new QTcpServer(this);
    ui->port->setText("80");
    ui->pushButton_2->setDisabled(true);
    connect(m_tcps,&QTcpServer::newConnection,this,&Widget::serve_new_connect);
    connect(this,&Widget::data_get,this,&Widget::serve_send_data);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_clicked()
{
    ui->pushButton->setDisabled(true);
    ui->pushButton_2->setEnabled(true);
    unsigned short port=ui->port->text().toUShort();
    m_tcps->listen(QHostAddress::Any,port);


}

void Widget::on_pushButton_2_clicked()
{
    ui->pushButton->setEnabled(true);
    ui->pushButton_2->setDisabled(true);

}

void Widget::serve_new_connect()
{
    if(clint_num<2)
    {
        tcpsocket=m_tcps->nextPendingConnection();

        tcp_sockets.append(tcpsocket);
        clint_num++;
        ui->textEdit->setText("已连接用户数量："+QString::number((clint_num)));
        connect(tcpsocket,&QTcpSocket::readyRead,this,&Widget::serve_read_data);
        if(clint_num==2)
            this->star_game();
        connect(tcpsocket,&QTcpSocket::disconnected,this,&Widget::disconnect_socket);


    }

}

void Widget::serve_read_data()
{

    for(int i=0;i<tcp_sockets.count();i++)
    {
        tcpsocket=tcp_sockets.at(i);
        buffer=tcpsocket->readAll();
        if(buffer.length()!=0)
        {

            ui->textEdit->append(buffer);
            emit this->data_get();
        }

    }
}

void Widget::serve_send_data()
{
    for(int i=0;i<tcp_sockets.count();i++)
    {
        tcpsocket=tcp_sockets.at(i);
        tcpsocket->write(buffer);
    }
}

void Widget::star_game()
{
    tcpsocket=tcp_sockets.at(0);
    tcpsocket->write("b");

    tcpsocket=tcp_sockets.at(1);
    tcpsocket->write("w");

    ui->textEdit->append("start");

}

void Widget::disconnect_socket()
{
    this->tcp_sockets.removeFirst();
    //this->tcp_sockets.removeFirst();
    clint_num=0;
    ui->textEdit->append("用户退出连接");

}
